import re
import tkinter as tk
from tkinter import *
from sympy import symbols, Eq, solve
from sympy.core.backend import sympify

# buttons = [
#     'x', 'y', 'z', 'x\u00B2', 'x\u00B3', 'x\u02B8',
#     '1', '2', '3', '\u207A/\u208B', 'e', '\u03C0',
#     '5', '6', '7', '+', '-', '*',
#     '8', '9', '0', '/', '.', '='
# 
# ]
subscript_map = {
    '0': '\u2080',
    '1': '\u2081',
    '2': '\u2082',
    '3': '\u2083',
    '4': '\u2084',
    '5': '\u2085',
    '6': '\u2086',
    '7': '\u2087',
    '8': '\u2088',
    '9': '\u2089'
}
result_express = ''


def extract_last_number(expression):
    # 使用正则表达式匹配最后一个数字
    match = re.search(r'\d+$', expression)
    if match:
        return int(match.group())
    else:
        return ''


def remove_last_number(expression):
    # 使用正则表达式移除最后一个数字
    return re.sub(r'\d+\s*$', '', expression)


def string_regularization(function):  # 此函数是为了解决x^2，x^3,这两个操作的问题的函数，将表达式转换为sympy可以处理的形式
    global result_express
    last_number = extract_last_number(result_express)
    front_exp = remove_last_number(result_express)
    result_express = front_exp + last_number + function


class SolvingEquations:

    def __init__(self, main_window):
        self._display = None
        self._buttons = None
        self._main_window = main_window
        self._window = tk.Toplevel(self._main_window)
        self._window.title("解方程")
        self._window.geometry("550x340")
        self._setup_ui()

    def _setup_ui(self):
        # 创建显示框
        self._display = Entry(self._window, width=27, bd=3, font=("Arial", 24), justify='right', relief=SUNKEN)
        self._display.grid(row=0, column=0, columnspan=6, sticky='ew', ipadx=5, ipady=40)

        # 按钮文本与功能的映射
        self._buttons = [
            '', '', '', '', '求解', 'AC',
            '(', ')', 'x', 'e', '\u03C0', '\u232B',
            '1', '2', '3', 'x\u00B2', 'x\u00B3', 'x\u02B8',
            '5', '6', '7', '+', '-', '*',
            '8', '9', '0', '/', '.', '='
        ]

        # 添加按钮到界面
        self._add_buttons()

    def _add_buttons(self):
        row_value, col_value = 1, 0
        for button_text in self._buttons:
            button = Button(self._window, text=button_text, font=('Arial', 10), width=9,
                            command=lambda text=button_text: self.on_button_click(text))
            button.grid(row=row_value, column=col_value, padx=3, pady=3, ipadx=2, ipady=2)
            col_value += 1
            if col_value > 5:
                row_value += 1
                col_value = 0

    def on_button_click(self, text):
        global result_express
        if text == '求解':
            x = symbols('x')
            right = sympify(result_express.split('=')[-1])
            left = sympify(result_express.split('=')[0])
            equation = Eq(left, right)
            solutions = solve(equation, x)
            result = ''
            for i in range(len(solutions)):
                if i != len(solutions) - 1:
                    result += 'X' + subscript_map[str(i + 1)] + '=' + str(solutions[i]) + ', '
                elif len(solutions) == 1:
                    result = 'X' + subscript_map[str(i + 1)] + '=' + 'X' + subscript_map[str(i + 2)] + '=' + str(
                        solutions[i])
                else:
                    result += 'X' + subscript_map[str(i + 1)] + '=' + str(solutions[i])

            self._display.delete(0, tk.END)
            self._display.insert(tk.END, result)
        elif text == 'x\u00B2':  # x^2
            string_regularization('**2')
            print(result_express)
            self._display.insert(tk.END, '\u00B2')
        elif text == 'x\u00B3':  # x^3
            string_regularization('**3')
            print(result_express)
            self._display.insert(tk.END, '\u00B3')
        elif text == 'x\u02B8':  # x^y
            string_regularization('**')
            print(result_express)
            self._display.insert(tk.END, '\u02B8')
        elif text == '\u03C0':
            result_express += 'math.pi'
        elif text == '\u232B':  # 退格功能
            self._display.delete(self._display.index(tk.END) - 1, tk.END)
        elif text == 'AC':
            self._display.delete(0, tk.END)
        else:
            self._display.insert(tk.END, text)
            result_express += text
